//
//  MQWelcomeViewController.swift
//  MQWeibo
//
//  Created by 毛强 on 15/12/30.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

class MQWelcomeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let headImageUrlString = MQUserAccountViewModel.sharedViewModel.userAccount?.avatar_large {
            headImage.sd_setImageWithURL(NSURL(string: headImageUrlString), placeholderImage: UIImage(named: "avatar_default_big"))
        }
        setupUI()
    }
    
    /// 初始化视图
    private func setupUI(){
        view.backgroundColor = UIColor(white: 247/255, alpha: 1)
        
        
        // 添加控件
        view.addSubview(headImage)
        view.addSubview(messageLabel)
        
        // 添加约束
        headImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view)
            make.top.equalTo(view).offset(200)
            make.size.equalTo(CGSizeMake(90, 90))
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(headImage)
            make.top.equalTo(headImage.snp_bottom).offset(10)
        }
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 改约束
        // 更新约束_update
        headImage.snp_updateConstraints { (make) -> Void in
            make.top.equalTo(view).offset(100)
        }
        
        // 执行动画
        // Damping: 阻尼 0-1 越大，弹性的幅度越小
        // initialSpringVelocity: 初始弹性速度
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in
            // 执行动画，要执行约束动画的话，一定是将 layoutIfNeeded 放在动画块
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                // 动画执行完毕
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.messageLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        // 透明度动画执行完毕
                        
                        // 在这需要跳转控制器
                        // 跳转到主页
                        // 发送通知，通知 appdelegate 去切换根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(MQSwitchRootViewControllerNotification, object: nil)
                })
        }
    }
    
    
    // MARK: - 懒加载控件
    
    // 头像
    private lazy var headImage: UIImageView = {
        let result = UIImageView(image: UIImage(named: "avatar_default_big"))
        result.layer.cornerRadius = 45
        result.layer.masksToBounds = true
        return result
    }()
    // 提示 label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 16)
        label.text = "欢迎回来"
        label.alpha = 0
        return label
    }()
    

}
